import Mock from 'mockjs'

// 模拟api接口
// Mock.mock('/api/user/list',{ list:[ {},{} ] })
// Mock.mock('/api/user/list',()=>{ return [] })
// Mock.mock('/api/user/list','get',()=>{ return [] })
// Mock.mock('/api/user/list','post',()=>{ return [] })

var data = {};

//生成数据
if (localStorage.getItem('user_list')) {
    data = JSON.parse(localStorage.getItem('user_list'))
} else {
    //生成数据
    data = Mock.mock({
        "list|8": [
            {
                'id|200010-200100': 1,
                name: '@name',
                Administrator: '系统管理员',
                name: '@cname',
                branch: '研发部',
                date: '@date',
                state: '启用|禁用'
            }
        ]
    })
    //保存数据到本地存储
    localStorage.setItem('user_list', JSON.stringify(data))
}

//查询接口
Mock.mock('/api/user/list', 'get', () => {
    //返回数据
    return data;
})

//删除接口
Mock.mock('/api/user/delete', 'post', (req) => {
    //接收参数 , req.body 是字符串格式,需要转为json对象
    // console.log( req.body );
    var { id } = JSON.parse(req.body);

    //通过id, 找到要删除的那一条数据, 执行删除
    var i = data.list.findIndex((item) => {
        return item.id == id;
    })
    if (i != -1) {
        data.list.splice(i, 1);
        localStorage.setItem('user_list', JSON.stringify(data));
    }

    return { status: 200, msg: '删除成功!', list: data.list }
})

Mock.mock('/api/user/create', 'post', (req) => {
    //接收参数 , req.body 是字符串格式,需要转为json对象
    // console.log(JSON.parse(req.body));
    var { username, name, branch } = JSON.parse(req.body);
    // console.log('添加',data.list);
    var id=data.list[data.list.length-1].id+1
    // //插入
    data.list.push(Mock.mock({
        id,
        username,
        name,
        branch,
        Administrator: '系统管理员',
        date: '@date',
        state: '启用|禁用'
    }));
    localStorage.setItem('user_list', JSON.stringify(data));
    return { status: 200, msg: '添加成功!', list: data.list }
})
//
Mock.mock('/api/user/redact', 'post', (req) => {
    //接收参数 , req.body 是字符串格式,需要转为json对象
    // console.log(JSON.parse(req.body));
    var { username, name, branch } = JSON.parse(req.body);
    // console.log('添加',data.list);
    var id=data.list.id
    // //插入
    data.list.rlplace(Mock.mock({
        id,
        username,
        name,
        branch,
        Administrator: '系统管理员',
        date: '@date',
        state: '启用|禁用'
    }));
    localStorage.setItem('user_list', JSON.stringify(data));
    return { status: 200, msg: '修改成功!', list: data.list }
})


